package manage.commons.result;

import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;

public class ExcelResult extends StrutsResultSupport {

	private static final long serialVersionUID = 796194350327671991L;
	public static final String DEFAULT_PARAM = "excelObject";
	public static final String CONTENTTYPE = "application/vnd.ms-excel";

	protected String excelObject = "wb";
	protected String fileName = "excel";
	protected HSSFWorkbook wb;
	protected boolean allowCaching = true;

	@Override
	protected void doExecute(String finalLocation, ActionInvocation invocation)
			throws Exception {
		ValueStack stack = invocation.getStack();
		String excelObject = stack.findString("excelObject");
		if (excelObject != null) {
			setExcelObject(excelObject);
		}
		String fileName = stack.findString("fileName");
		if (fileName != null) {
			setFileName(fileName);
		}
		OutputStream out = null;
		try {
			wb = (HSSFWorkbook) invocation.getStack().findValue(
					conditionalParse(getExcelObject(), invocation));
			if (wb == null) {
				throw new RuntimeException("没有导出的对象...");
			}
			HttpServletResponse response = (HttpServletResponse) invocation
					.getInvocationContext().get(HTTP_RESPONSE);
			response.setContentType(conditionalParse(ExcelResult.CONTENTTYPE,
					invocation));
			if (this.fileName != null) {
				String contentDisposition = "attachment;filename="
						+ this.fileName + ".xls";
				response.addHeader("Content-Disposition",
						conditionalParse(contentDisposition, invocation));
			}
			if (!this.allowCaching) {
				response.addHeader("Pragma", "no-cache");
				response.addHeader("Cache-Control", "no-cache");
			}
			out = response.getOutputStream();
			wb.write(out);
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			throw new RuntimeException("导出excel文件出错...");
		} finally {
			out.close();
			this.wb = null;
		}
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public boolean isAllowCaching() {
		return allowCaching;
	}

	public void setAllowCaching(boolean allowCaching) {
		this.allowCaching = allowCaching;
	}

	public String getExcelObject() {
		return excelObject;
	}

	public void setExcelObject(String excelObject) {
		this.excelObject = excelObject;
	}

}
